package angle.controller;

import angle.pojo.Bill;
import angle.pojo.Provider;
import angle.pojo.User;
import angle.service.bill.BillService;
import angle.service.provider.ProviderService;
import angle.tools.PageSupport;
import com.alibaba.fastjson.JSONArray;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/bill")
public class BillController {

    @Autowired
    private BillService billService;

    @Autowired
    private ProviderService providerService;

    /*实现订单列表页面,动态实现订单删除*/
    @RequestMapping("/billlist")
    public ModelAndView billList(HttpServletRequest req, HttpServletResponse resp) {
        ModelAndView mav = new ModelAndView();
        //从前端获取数据
        String method = req.getParameter("method");
        if (method.equals("query") && method != null) {
            //从前端获取数据
            String queryProductName = req.getParameter("queryProductName");
            String queryProviderId = req.getParameter("queryProviderId");
            String queryIsPayment = req.getParameter("queryIsPayment");
            String pageIndex = req.getParameter("pageIndex");
            //设置每页到显示个数
            int pageSize = 5;
            //设置当前页面值
            int currentPageNo = 1;
            Map<String, Object> map = new HashMap<String, Object>();
            //防止商品名称、供应商id，是否支付传入空字符串，从而导致动态sql错误拼接从而查询失败
            if (queryProductName != null && !queryProductName.equals("")) {
                map.put("productName",queryProductName);
            }else {
                map.put("productName",null);
            }
            if (queryProviderId != null && !queryProviderId.equals("")) {
                map.put("providerId",Integer.parseInt(queryProviderId));
            }else {
                map.put("providerId",0);
            }
            if (queryIsPayment != null && !queryIsPayment.equals("")) {
                map.put("isPayment",Integer.parseInt(queryIsPayment));
            }else {
                map.put("isPayment",0);
            }
            //判断页面到当前页，保证页面数不为空
            if (pageIndex != null) {
                try {
                    currentPageNo = Integer.parseInt(pageIndex);
                } catch (Exception e) {
                    mav.setViewName("redirect:/error.jsp");
                    return mav;
                }
            }
            map.put("currentPageNo", (currentPageNo - 1) * pageSize);
            map.put("pageSize", pageSize);
            //获取用户总数
            int totalCount = billService.getBillCountByProId(0);
            //分页实现
            PageSupport pageSupport = new PageSupport();
            pageSupport.setCurrentPageNo(currentPageNo);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalCount(totalCount);
            //获取页面总数
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首尾页跳转
            if (currentPageNo < 1) {
                currentPageNo = 1;
            } else if (currentPageNo > totalPageCount) {
                currentPageNo = totalPageCount;
            }
            //获取订单列表
            List<Bill> billList = billService.getBillList(map);
            //查出每个订单对应的供应商名称
            for (Bill bill : billList) {
                Provider provider = new Provider();
                provider.setId(bill.getProviderId());
                bill.setProviderName((providerService.queryProById(provider)).getProName());
            }
            //获取供应商列表（这里的map相当于一个空值）
            List<Provider> providerList = providerService.getProListNoLimit(map);
            //给试图层传递参数
            mav.addObject("providerList", providerList);
            mav.addObject("billList", billList);
            mav.addObject("totalCount", totalCount);
            mav.addObject("currentPageNo", currentPageNo);
            mav.addObject("totalPageCount", totalPageCount);
            //保证再点击查询之后，查询框中到内容还在
            mav.addObject("queryProductName", queryProductName);
            mav.addObject("queryProviderId", queryProviderId);
            mav.addObject("queryIsPayment", queryIsPayment);
            mav.setViewName("billlist");
        }
        /*ajax动态删除用户实现*/
        else if (method.equals("delbill") && method != null) {
            String id = req.getParameter("billid");
            Integer delId = 0;
            try {
                delId = Integer.parseInt(id);
            } catch (Exception e) {
                delId = 0;
            }
            Map<String, String> resultMap = new HashMap<String, String>();
            if (delId <= 0) {
                resultMap.put("delResult", "notexist");
            } else {
                if (billService.deleteBillById(delId) > 0) {
                    resultMap.put("delResult", "true");
                } else {
                    resultMap.put("delResult", "false");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                resp.setContentType("application/json;charset=utf-8");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = resp.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
            mav.setViewName("billlist");
        }
        return mav;
    }

    /*跳转到订单添加界面*/
    @RequestMapping("/tobilladd")
    public String toBillAdd(){
        return "billadd";
    }

    /*实现订单添加*/
    @RequestMapping(value = "/billadd", produces = "application/json; charset=utf-8")
    public ModelAndView billAdd(Bill bill, HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mav = new ModelAndView();
        String method = request.getParameter("method");
        //当method为add时，代表全部输入合法，成功添加
        if (method.equals("add") && method != null) {
            bill.setCreationDate(new Date());
            bill.setCreatedBy(((User) request.getSession().getAttribute("user")).getId());
            int flag = 0;
            flag = billService.billAdd(bill);
            if (flag > 0) {
                mav.setViewName("redirect:/bill/billlist?method=query");
            } else {
                mav.setViewName("billadd");
            }
        }
        //ajax动态获取供应商栏参数
        else if (method.equals("getproviderlist") && method != null) {
            List<Provider> providerList = providerService.getProListNoLimit(new HashMap<String, Object>());
            try {
                //将roleList转换成json对象
                response.setContentType("application/json;charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONArray.toJSONString(providerList));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //ajax动态验证登录账号billCode是否已经存在
        else if (method.equals("bcexist") && method != null) {
            //判断订单编码是否可用
            String billCode = request.getParameter("billCode");
            //用于存放对billCode判断对结果
            Map<String, String> resultMap = new HashMap<String, String>();
            //判断billCode是否为空
            if (StringUtils.isNullOrEmpty(billCode) || billCode == "") {
                resultMap.put("billCode", "empty");
            } else {
                Bill bill1 = new Bill();
                bill1.setBillCode(billCode);
                bill1 = billService.queryBillById(bill1);
                if (null != bill1) {
                    resultMap.put("billCode", "exist");
                } else {
                    resultMap.put("billCode", "notexist");
                }
            }
            try {
                //把resultMap转为json字符串以json的形式输出
                //配置上下文的输出类型
                response.setContentType("application/json");
                //从response对象中获取往外输出的writer对象
                PrintWriter outPrintWriter = response.getWriter();
                //把resultMap转为json字符串 输出
                outPrintWriter.write(JSONArray.toJSONString(resultMap));
                outPrintWriter.flush();//刷新
                outPrintWriter.close();//关闭流
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return mav;
    }

    /*实现订单查看详情*/
    @RequestMapping("/billview")
    public ModelAndView BillView(int billid) {
        ModelAndView mav = new ModelAndView();
        Bill bill = new Bill();
        //根据id查询出当前选中的供应商
        bill.setId(billid);
        bill = billService.queryBillById(bill);
        Provider provider = new Provider();
        provider.setId(bill.getProviderId());
        bill.setProviderName((providerService.queryProById(provider)).getProName());
        //将数据传入前端
        mav.addObject("bill", bill);
        mav.setViewName("billview");
        return mav;
    }

    /*跳转到供应商修改页面*/
    @RequestMapping("/tobillmodify")
    public ModelAndView toBillModify(int billid) {
        ModelAndView mav = new ModelAndView();
        Bill bill = new Bill();
        //根据id查询出当前选中的供应商
        bill.setId(billid);
        bill = billService.queryBillById(bill);
        //将数据传入前端
        mav.addObject("bill", bill);
        mav.setViewName("billmodify");
        return mav;
    }

    /*实现订单修改*/
    @RequestMapping("/billmodify")
    public ModelAndView BillModify(Bill bill,HttpServletRequest req){
        ModelAndView mav = new ModelAndView();
        //因为code设置为readonly，所以要将其手动注入对象属性中
        /*bill.setBillCode(req.getParameter("billCode"));*/
        //将修改者和修改时间注入对象属性中
        bill.setModifyBy(((User)req.getSession().getAttribute("user")).getId());
        bill.setModifyDate(new Date());
        int flag = billService.modifyBillById(bill);
        if (flag > 0){
            mav.setViewName("redirect:/bill/billlist?method=query");
        }else {
            mav.setViewName("redirect:/bill/tobillmodify");
        }
        return mav;
    }
}
